//
//  SearchResultVC.m
//  PeanutEbuy
//
//  Created by 赵甜 on 2020/4/11.
//  Copyright © 2020 赵甜. All rights reserved.
//

#import "SearchResultVC.h"
#import "HMSegmentedControl.h"
#import "MailProductCell.h"
#import "MJRefresh.h"
#import "SearchResultModel.h"
#import "ZTnavigationBar.h"
#import "TCBabyDeailtyRootVC.h"


@interface SearchResultVC ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

@property(nonatomic, strong)ZTnavigationBar * ztNavigationBar;
@property (nonatomic,strong) HMSegmentedControl *segmentedControl;
@property(nonatomic, strong) UITableView *tv;

@property (nonatomic,strong) NSMutableArray *product_list;
@property (nonatomic,assign) int  pagenum;
@property (nonatomic,assign) int  pagesize;
@property (nonatomic,strong) NSString * common;
@property (nonatomic,strong) NSString * asc;
@property (nonatomic,assign) int  firstSelectPrice;






@end

@implementation SearchResultVC



- (void)viewDidLoad {
    [super viewDidLoad];

    
    _product_list = [[NSMutableArray alloc]init];
    self.pagenum  = 1;
    self.pagesize = 20;
    _common =@"common";
    _asc = @"asc";
    _firstSelectPrice = 0;
    
    [self addCustomNaV];
    
    [self initSegmentedControl];

    [self CreatTableView];
    
    self.segmentedControl.selectedSegmentIndex = 0;
    [self.tv .mj_header beginRefreshing];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES; // 使右滑返回手势可用
    self.navigationController.navigationBar.hidden = YES; // 隐藏导航
}

-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO; // 隐藏导航
    self.hidesBottomBarWhenPushed = NO;
}

-(void)addCustomNaV{
    _ztNavigationBar = [ZTnavigationBar instanceView];
//  _ztNavigationBar.ztsearchBar.placeholder =@"搜索您想找的商品";
    [_ztNavigationBar.citybtn setImage:[UIImage imageNamed:@"icon-back"] forState:UIControlStateNormal];
    [_ztNavigationBar.citybtn  setTitle:@"" forState:UIControlStateNormal];
    _ztNavigationBar.citybtn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    [_ztNavigationBar.carBtn setHidden:YES];
    [_ztNavigationBar.messageBtn setHidden:YES];
    
    WeakSelf;
    _ztNavigationBar.carBtnBlcok = ^{
       };
    _ztNavigationBar.messageBtnBlcok = ^{
    };
    _ztNavigationBar.cityBtnBlcok = ^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    
    _ztNavigationBar.ztsearchBar.delegate =self;

    _ztNavigationBar.beginEditingBlcok = ^{
    //    [weakSelf.ztNavigationBar.ztsearchBar.searchTextField becomeFirstResponder];
    //    dispatch_async(dispatch_get_main_queue(), ^{
    //    //开始编辑
    //    });
    };


    if (!self.ztNavigationBar.hidden) {
        [self.view addSubview:self.ztNavigationBar];
        [_ztNavigationBar update];
    
        [_ztNavigationBar.citybtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(viewBottom(_ztNavigationBar)-44);
            make.left.equalTo(_ztNavigationBar.mas_left);
            make.height.offset(44);
            make.width.offset(30);
        }];
        [_ztNavigationBar.ztsearchBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(viewBottom(_ztNavigationBar)-44);
            make.left.equalTo(_ztNavigationBar.citybtn.mas_right);
            make.height.offset(44);
            make.right.equalTo(_ztNavigationBar.mas_right).offset(-10);
        }];
    }
}




- (void)initSegmentedControl {
    //这个傻逼的组件，当初就不该拉进来用。太LOW
    NSString *unarriveCountStr = [NSString stringWithFormat:@"%@",@"综合"];
    NSString *arriveCountStr = [NSString stringWithFormat:@"%@",@"销量"];
    NSString *invalidCountStr = [NSString stringWithFormat:@"%@",@"价格"];
//  self.segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[unarriveCountStr, arriveCountStr,invalidCountStr]];
    UIImage * iamge1 = [UIImage imageNamed:@"sorting_img"];
    UIImage * iamge2 = [UIImage imageNamed:@"sorting_img"];
    UIImage * iamge3 = [UIImage imageNamed:@"sorting_img"];
    NSNumber * index = [NSNumber numberWithInt:2];
    NSMutableArray * array = [[NSMutableArray alloc]init];
    [array addObject:index];
    
    self.segmentedControl = [[HMSegmentedControl alloc] initWithSectionImages:@[iamge1,iamge2,iamge3] sectionSelectedImages:nil titlesForSections:@[unarriveCountStr, arriveCountStr,invalidCountStr] showAllImage:NO showIndexArray:array];
    
    self.segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
    self.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
    self.segmentedControl.backgroundColor = [UIColor whiteColor];
    self.segmentedControl.selectionIndicatorHeight = 3.f;
    self.segmentedControl.selectionIndicatorEdgeInsets = UIEdgeInsetsMake(0, 0, -5, 0);
    self.segmentedControl.selectionIndicatorColor = [UIColor mainBlueColor];
    self.segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    WeakSelf;
    [self.segmentedControl setTitleFormatter:^NSAttributedString *(HMSegmentedControl *segmentedControl, NSString *title, NSUInteger index, BOOL selected) {

        NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:title];
        [attString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:NSMakeRange(0, title.length)];
        [attString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, title.length)];

        NSRange titleRange = NSMakeRange(0, 0);
        switch (index) {
            case 0:
                titleRange = [title rangeOfString:@"未到访"];
                break;
            case 1:
                titleRange = [title rangeOfString:@"已到访"];
                break;
            case 2:
                titleRange = [title rangeOfString:@"已失效"];
                break;
            case 3:
                titleRange = [title rangeOfString:@"全部"];
                break;
        }

        UIColor *selectedColor = selected ? [UIColor whiteColor]:[UIColor blackColor];
        [attString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:titleRange];
        [attString addAttribute:NSForegroundColorAttributeName value:selectedColor range:titleRange];
        return attString;

    }];
//排序综合:common,销量:sale,价格price,默认common
    
    [self.segmentedControl setIndexChangeBlock:^(NSInteger index) {
        switch (index) {
            case 0:
                weakSelf.common = @"common";
                weakSelf.asc = @"asc";
                break;
            case 1:
                weakSelf.common = @"sale";
                weakSelf.asc = @"asc";
                break;
            case 2:
                weakSelf.common = @"price";
                if (weakSelf.firstSelectPrice == 0) {
                    weakSelf.asc = @"asc";
                    weakSelf.firstSelectPrice +=1;
                }else{
                    weakSelf.asc = @"desc";//降序
                    weakSelf.firstSelectPrice -=1;
                }
                break;
            default:
                break;
        }
        [weakSelf.tv.mj_header beginRefreshing];
    }];
    [self.view addSubview:self.segmentedControl];
    [self.segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.ztNavigationBar.mas_bottom);
        make.height.offset(42);
    }];

    
}

-(void)CreatTableView{
    UITableViewStyle style;
      if (@available(iOS 13.0, *)) {
          style =UITableViewStyleInsetGrouped;
      } else {
          style = UITableViewStyleGrouped;
      }
    _tv = [[UITableView alloc]initWithFrame:CGRectZero style:style];

    _tv.backgroundColor = [UIColor mainBackgroundColor];
    _tv.separatorStyle = UITableViewCellSeparatorStyleNone;

    _tv.delegate = self;
    _tv.dataSource = self;
    [_tv registerNib:[UINib nibWithNibName:@"MailProductCell" bundle:nil] forCellReuseIdentifier:NSStringFromClass([MailProductCell class])];
    _tv.sectionHeaderHeight = 0;
    _tv.sectionFooterHeight = 10;
    _tv.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 10)];
    _tv.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    [self.view addSubview:self.tv];
    [self.tv mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(self.segmentedControl.mas_bottom);
         make.left.equalTo(self.view);
         make.bottom.equalTo(self.view);
         make.right.equalTo(self.view);
     }];
    
        WeakSelf;
      _tv.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
          weakSelf.pagenum = 1;
          [weakSelf get_GoodsList];
          
      }];
      
      self.tv.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
          
          weakSelf.pagenum += 1;
          [weakSelf get_GoodsList];
          
      }];
      self.tv.mj_footer.hidden = YES;
}

#pragma mark - 数据接口
//搜索商品结果列表
-(void)get_GoodsList{
    WeakSelf;
    [ZTHttp search_Goods:_keyword orderBy:_common ascOrDesc:_asc pageNum:_pagenum pageSize:_pagesize success:^(NSDictionary * _Nullable dic) {
        if (dic) {
            [weakSelf.tv.mj_header endRefreshing];
            [weakSelf.tv.mj_footer endRefreshing];
            
            NSDictionary * dataDic = [NSDictionary dictionaryWithDictionary:[dic objectForKey:@"data"]];
            NSMutableArray * list_array =[SearchResultModel mj_objectArrayWithKeyValuesArray:[dataDic objectForKey:@"result"]];
            if (weakSelf.pagenum ==1) {
                weakSelf.product_list = [list_array copy];
            }else{
                [weakSelf.product_list addObjectsFromArray:list_array];
            }
            
            if (weakSelf.product_list.count >= 1) {
                weakSelf.tv.mj_footer.hidden = NO;
            }else {
                weakSelf.tv.mj_footer.hidden = YES;
            }
            
            NSNumber * total= [dataDic objectForKey:@"total"];
            if (total.intValue == weakSelf.product_list.count) {
               [weakSelf.tv.mj_footer endRefreshingWithNoMoreData];
            }
            [weakSelf.tv reloadData];
        }
    } failure_Nonnull:^(NSDictionary * _Nonnull dic) {
        [weakSelf.tv .mj_header endRefreshing];
        [weakSelf.tv .mj_footer endRefreshing];
    }];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    ZTLog(@"测试");
    return YES;
}                      // return NO to not become first responder



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _product_list.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 95;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MailProductCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MailProductCell class])];
    if(!cell){
        cell = [[NSBundle mainBundle]loadNibNamed:@"MailProductCell" owner:nil options:nil].firstObject;
    }
    cell.productNumView.hidden = YES;
    SearchResultModel * model = [_product_list objectAtIndex:indexPath.section];
    
    [cell.cell_imgV sd_setImageWithURL:[NSURL URLWithString:model.mainImgUrl]];
    cell.nameLabel.text = model.goodsName;
    cell.detailLabel.text = model.detailContent;
//    float prices = model.goodsPrice.floatValue;
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%.2f",model.goodsPrice.floatValue/100];

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SearchResultModel * model = [_product_list objectAtIndex:indexPath.section];

    TCBabyDeailtyRootVC * CTL =  [[TCBabyDeailtyRootVC alloc]init];
    CTL.goodsNo = model.goodsNo;
    [self.navigationController pushViewController:CTL animated:YES];

}


@end
